<?php

namespace App\Http\Middleware;

use App\Wen\Utils\Settings;
use Closure;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\BaseController;
use Illuminate\Support\Facades\Log;

class AdminCodeAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        global $__MINI_GLOBAL_IP__;
        $token = $request->header('admin-token','');
        if($__MINI_GLOBAL_IP__ == ''){
            if(_empty_($request->header('X-Forwarded-For',''))){
                $__MINI_GLOBAL_IP__ = $request->ip();
            }else{
                $__MINI_GLOBAL_IP__ = $request->header('X-Forwarded-For','');
            }
        }
        if(!$token){
            $baseController = new BaseController();
            return $baseController->fail(503002);
        }
        if(Settings::get('admin_auth_code') != $token){
            $baseController = new BaseController();
            return $baseController->fail(503003);
        }

        if(_empty_($request->domain) || preg_match('$/|:|(http)$', $request->domain)){
            $baseController = new BaseController();
            return $baseController->fail(1001007);
        }

        if(_empty_($request->id)){
            // 不是批量
            if(_empty_($request->actions)){
                $baseController = new BaseController();
                return $baseController->fail(1001002, []);
            }
        }

        return $next($request);
    }
}
